﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pg.BioMedics.SDR.Caching
{
    /// <summary>
    /// Cachning strategy utilizing local memory as a store for the 
    /// cached objects
    /// </summary>
    internal class LocalCachingStrategy<T> : ICachingStrategy<T>
    {
        #region Fields

        /// <summary>
        /// Items container utilzied by this strategy for holding 
        /// entities
        /// </summary>
        private IDictionary<string, T> container = new Dictionary<string, T>();

        #endregion

        #region ICachingStrategy<T> Members

        /// <summary>
        /// Puts a new item of type T into the cache. A new item is 
        /// defined by its unique key.
        /// </summary>
        /// <param name="key">Unique item key</param>
        /// <param name="item">Item instance</param>
        public void Put(string key, T item)
        {
            if (this.container.ContainsKey(key))
                this.container.Remove(key);

            this.container.Add(key, item);
        }

        /// <summary>
        /// Checks if the given key is present in the cache
        /// </summary>
        /// <param name="key">Unique key</param>
        /// <returns>true - if item belongs already to the cache</returns>
        public bool Contains(string key)
        {
            return this.container.ContainsKey(key);
        }

        /// <summary>
        /// Removes item assigned to the given key from the cache
        /// </summary>
        /// <param name="key"></param>
        public void Remove(string key)
        {
            this.container.Remove(key);
        }

        /// <summary>
        /// Removes all items from the cache
        /// </summary>
        public void Clear()
        {
            this.container.Clear();

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        /// <summary>
        /// Gets IQueryable related with this strategy
        /// </summary>
        /// <returns>IQueryable implementation</returns>
        public IQueryable<T> GetQueryable()
        {
            return this.container.Values.AsQueryable<T>();
        }

        #endregion
    }
}
